--[[
	cargMapDisplay
		A VERY simple LDB display-addon which sits next to the world map close button
]]

local lib, oldminor = LibStub:NewLibrary("cargMapDisplay", 1)
if not lib then return end

local ldb = LibStub:GetLibrary("LibDataBroker-1.1")

local objects = {}
local curr

local function GetTipAnchor(frame)
	local x,y = frame:GetCenter()
	if not x or not y then return "TOPLEFT", "BOTTOMLEFT" end
	local hhalf = (x > UIParent:GetWidth()*2/3) and "RIGHT" or (x < UIParent:GetWidth()/3) and "LEFT" or ""
	local vhalf = (y > UIParent:GetHeight()/2) and "TOP" or "BOTTOM"
	return vhalf..hhalf, frame, (vhalf == "TOP" and "BOTTOM" or "TOP")..hhalf
end

local frame = CreateFrame("Button", "cargMapDisplay", WorldMapFrame)
frame:SetPoint("RIGHT", WorldMapFrameCloseButton, "LEFT", -10, 0)
frame:SetWidth(100)
frame:SetHeight(20)
frame:EnableMouse(true)
frame:SetMovable(false)

frame.text = frame:CreateFontString(nil, "OVERLAY")
frame.text:SetFontObject(GameFontNormal)
frame.text:SetShadowOffset(1,-1)
frame.text:SetAllPoints(frame)
frame:RegisterForClicks("anyUp")

local updateDisplay = function(event, name, attr, value, dataobj)
	if(type(event) == "table") then dataobj = event end
	if(dataobj == objects[curr]) then
		frame.text:SetText(dataobj.text)
		frame:SetWidth(frame.text:GetStringWidth()+10)
	end
end

frame:SetScript("OnEnter", function(self)
	if(curr and objects[curr] and objects[curr].OnTooltipShow) then
		WorldMapTooltip:SetOwner(self, GetTipAnchor(self))
		objects[curr].OnTooltipShow(WorldMapTooltip)
		if(#objects > 1) then
			WorldMapTooltip:AddLine("")
			WorldMapTooltip:AddLine("Click to change info display.")
		end
		WorldMapTooltip:Show()
	end
end)
frame:SetScript("OnLeave", function() WorldMapTooltip:Hide() end)
frame:SetScript("OnClick", function()
	if(not curr) then return nil end
	curr = (curr >= #objects) and 1 or (curr + 1)
	updateDisplay(objects[curr])
end)

function lib:RegisterObject(name)
	assert(ldb:GetDataObjectByName(name), "cargMapDisplay: '"..name.."' is not a valid LDB-dataobject")
	tinsert(objects, ldb:GetDataObjectByName(name))
	ldb.RegisterCallback(lib, "LibDataBroker_AttributeChanged_"..name.."_text", updateDisplay)
	curr = #objects
end
